package io.github.maojian.arr;

import org.junit.Test;

/**
 * 670. 最大交换
 * 给定一个非负整数，你至多可以交换一次数字中的任意两位。返回你能得到的最大值。
 */
public class Q670 {
    public int maximumSwap(int num) {
        char[] chars = String.valueOf(num).toCharArray();
        int length = chars.length;
        int maxNum = 0, maxNumIndex = 0;
        for (int i = 0; i < length; i++) {
            if (chars[i] >= maxNum) {
                maxNum = chars[i];
                maxNumIndex = i;
            }
        }
        for (int i = 0; i < maxNumIndex; i++) {
            if (chars[i] < maxNum) {
                int temp = chars[i];
                chars[i] = (char) maxNum;
                chars[maxNumIndex] = (char) temp;
                return Integer.parseInt(new String(chars));
            }
        }
        return num;
    }

    @Test
    public void test() {
        int num = 9973;
        System.out.println(maximumSwap(num));
    }
}
